package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/spf13/cast"
	"goravel/app/models"
	"strconv"
)

type KilllogController struct {
	//Dependent services
	SearchByParamsService
}

func NewKilllogController() *KilllogController {
	return &KilllogController{
		//Inject services
	}
}

func (r *KilllogController) Index(ctx http.Context) http.Response {
	configuration_id := ctx.Value("configuration_id").(string)

	pageSize := ctx.Request().Query("pageSize", "1")
	pageSizeInt, _ := strconv.Atoi(pageSize)
	order := ctx.Request().Query("order")
	sort := ctx.Request().Query("sort")
	killLogs := []models.KillLog{}
	var total int64
	currentPage := ctx.Request().Query("currentPage", "1")
	currentPageInt, _ := strconv.Atoi(currentPage)
	queries := ctx.Request().Queries()
	if order != "" || sort != "" {
		facades.Orm().Query().Where("configuration_id", cast.ToInt(configuration_id)).Scopes(r.SearchByParams(ctx.Request().Queries())).Order(sort+" "+order).Paginate(currentPageInt, pageSizeInt, &killLogs, &total)
	} else {
		facades.Orm().Query().Where("configuration_id", cast.ToInt(configuration_id)).Scopes(r.SearchByParams(queries)).Order("id desc").Paginate(currentPageInt, pageSizeInt, &killLogs, &total)
	}

	return ctx.Response().Success().Json(http.Json{
		"data":  killLogs,
		"total": total,
		"links": map[string]interface{}{
			"first": "http://" + ctx.Request().Host() + "/api/loginlog?pageSize=" + pageSize + "&currentPage=1",
			//最后一页应该是总数除以每页的数量取整
			"last": "http://" + ctx.Request().Host() + "/api/loginlog?pageSize=" + pageSize + "&currentPage=" + strconv.Itoa(int(total)/pageSizeInt),
			"prev": "http://" + ctx.Request().Host() + "/api/loginlog?pageSize=" + pageSize + "&currentPage=" + strconv.Itoa(currentPageInt-1),
			"next": "http://" + ctx.Request().Host() + "/api/loginlog?pageSize=" + pageSize + "&currentPage=" + strconv.Itoa(currentPageInt+1),
		},
		"meta": map[string]interface{}{
			"total_page":   int(total) / pageSizeInt,
			"current_page": currentPageInt,
			"per_page":     pageSizeInt,
			"total":        total,
		},
	})
}
